package com.cy.detectsys.controller.detect;

import com.cy.detectsys.mapper.TcTaskMapper;
import com.cy.detectsys.service.DetectDataProcessService;
import com.cy.detectsys.service.ErrLogService;
import com.cy.detectsys.util.MinioTemplate;
import com.cy.detectsys.util.R;
import jakarta.annotation.Resource;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

import static com.cy.detectsys.constant.LocalPathContant.BATH_PATH;
import static com.cy.detectsys.constant.PackagePasswordConstant.PASSWORD;


@RestController
@RequestMapping("data")
public class ProcessZipController {

    @Resource
    private DetectDataProcessService processDataService;

    @Resource
    private MinioTemplate minioTemplate;

    @RequestMapping("detect/process")
    public R processDetectData(@RequestParam String filePath) {

        new Thread(() -> {


            // 下载数据文件
            String zipFilePath = downloadResultZip(filePath);

            // 解压数据
            unzip(zipFilePath, PASSWORD);

            // 处理数据
            processDataService.prepareData(zipFilePath);

            // 修改任务状态
            updateTaskStatus(zipFilePath);


        }).start();


        return R.ok();

    }


    @Resource
    private TcTaskMapper tcTaskMapper;
    private void updateTaskStatus(String zipFilePath) {
        //根据路径分解出任务编号
        String taskNum = new File(zipFilePath).getName().replace(".zip", "");

        //更新任务状态
        tcTaskMapper.updateByTaskNum(taskNum);


    }

    @Resource
    private ErrLogService errLogService;

    private void unzip(String zipPath, String password) {

        try {
            ZipFile zipFile = new ZipFile(zipPath, password.toCharArray());
            zipFile.setRunInThread(true);
            String targetPath = zipPath.replace(".zip", "");
            zipFile.extractAll(targetPath);
        } catch (ZipException e) {
            errLogService.small_err("文件解压失败" + zipPath);
        }

    }

    private String downloadResultZip(String filePath) {
        File file = new File(filePath);
        return minioTemplate.downloadFileFromMinio(filePath, BATH_PATH + File.separator + file.getName());
    }
}
